package com.studyv3.test.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyv3.common.core.page.PageQuery;
import com.studyv3.common.core.page.TableDataInfoPlus;
import com.studyv3.common.exception.ServiceException;
import com.studyv3.common.utils.StringUtils;
import com.studyv3.framework.lock.DistributedLock;
import com.studyv3.test.constants.LaoBaoConstants;
import com.studyv3.test.domain.ApplyWaste;
import com.studyv3.test.domain.Batch;
import com.studyv3.test.domain.Products;
import com.studyv3.test.domain.Stock;
import com.studyv3.test.domain.bo.ApplyWasteBo;
import com.studyv3.test.domain.vo.ApplyWasteVo;
import com.studyv3.test.mapper.ApplyWasteMapper;
import com.studyv3.test.mapper.BatchMapper;
import com.studyv3.test.mapper.ProductsMapper;
import com.studyv3.test.mapper.StockMapper;
import com.studyv3.test.service.ApplyWasteService;
import lombok.RequiredArgsConstructor;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * _报废申请/审批Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-07
 */
@RequiredArgsConstructor
@Service
public class ApplyWasteServiceImpl extends ServiceImpl<ApplyWasteMapper, ApplyWaste> implements ApplyWasteService {

    private final ApplyWasteMapper baseMapper;
    private final ProductsMapper productsMapper;
    private final BatchMapper batchMapper;
    private final StockMapper stockMapper;

    private final RedissonClient redissonClient;

    /**
     * 更新时加锁
     *
     * @param stock
     * @return
     */
    public Boolean updateStockWithLock(Stock stock) {
        // 获取锁 锁的key为 库存id+批次id

        RLock lock = redissonClient.getLock(String.valueOf(stock.getProductsId() + stock.getBatchId()));

        // 创建红锁客户端
        RedissonRedLock redissonRedLock = new RedissonRedLock(lock);
        //定义获取锁标志位,默认是获取失败
        boolean isLockBoolean = false;

        try {
            /**
             * waitTime：等待获取锁的最长时间。如果在等待时间内无法获取锁，并且没有其他锁释放，则返回 false。如果 waitTime < 0，则无限期等待，直到获得锁定。
             * leaseTime：就是redis key的过期时间，锁的持有时间，可以使用 ttl  查看过期时间。
             * 如果在持有时间结束前锁未被释放，则锁将自动过期，没有进行key续期，并且其他线程可以获得此锁。如果 leaseTime = 0，则锁将永久存在，直到被显式释放。
             */
            isLockBoolean = redissonRedLock.tryLock(1, 0, TimeUnit.SECONDS);
            if (isLockBoolean) {
                //业务逻辑，
                System.out.println("获取锁成功");
                return stockMapper.updateById(stock) > 0;
            }

        } catch (Exception e) {
            System.out.println("获取锁失败");
        } finally {
            //释放锁
            redissonRedLock.unlock();
        }
        return isLockBoolean;
    }

    /**
     * 查询_报废申请/审批
     */
    @Override
    public ApplyWasteVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询_报废申请/审批列表
     */
    @Override
    public TableDataInfoPlus<ApplyWasteVo> queryPageList(ApplyWasteBo bo, PageQuery pageDomain) {
        LambdaQueryWrapper<ApplyWaste> lqw = buildQueryWrapper(bo);
        Long aLong = baseMapper.selectCount(lqw);
        if (ObjectUtil.isAllNotEmpty(pageDomain.getPageNum(), pageDomain.getPageSize())){
            int page = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
            lqw.last("limit " + page + "," + pageDomain.getPageSize());
        }
        lqw.orderByDesc(ApplyWaste::getBatchId,ApplyWaste::getCreateTime);
        List<ApplyWasteVo> result = baseMapper.selectVoList(lqw);
        result.forEach(applyWasteVo -> {
            LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = new LambdaQueryWrapper<>();
            stockLambdaQueryWrapper.eq(Stock::getProductsId, applyWasteVo.getProductsId());
            stockLambdaQueryWrapper.eq(Stock::getBatchId, applyWasteVo.getBatchId());
            List<Stock> stocks = stockMapper.selectList(stockLambdaQueryWrapper);
            if (ObjectUtil.isNotEmpty(stocks)){
                Stock stock = stocks.get(0);
                applyWasteVo.setProductsUnqualified(stock.getProductsUnqualified());
                applyWasteVo.setProductsApply(stock.getProductsApply());
                applyWasteVo.setProductsNum(stock.getProductsNum());
            }
        });
        TableDataInfoPlus<ApplyWasteVo> build = TableDataInfoPlus.build(result);
        build.setTotal(aLong);
        return build;
    }

    @Override
    public TableDataInfoPlus<ApplyWasteVo> queryPageListSelf(ApplyWasteBo bo, PageQuery pageDomain) {
        LambdaQueryWrapper<ApplyWaste> lqw = buildQueryWrapper(bo);

        Page<ApplyWasteVo> applyWasteVoIPage = baseMapper.selectVoPage(pageDomain.build(), lqw);

        return TableDataInfoPlus.build(applyWasteVoIPage);
    }

    /**
     * 查询_报废申请/审批列表
     */
    @Override
    public List<ApplyWasteVo> queryList(ApplyWasteBo bo) {
        LambdaQueryWrapper<ApplyWaste> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ApplyWaste> buildQueryWrapper(ApplyWasteBo bo) {
        LambdaQueryWrapper<ApplyWaste> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getApplicant()), ApplyWaste::getApplicant, bo.getApplicant());
        lqw.like(StringUtils.isNotBlank(bo.getObjectName()), ApplyWaste::getObjectName, bo.getObjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getObjectAmount()), ApplyWaste::getObjectAmount, bo.getObjectAmount());
        lqw.eq(bo.getFlag() != null, ApplyWaste::getFlag, bo.getFlag());
        lqw.eq(bo.getDeleted() != null, ApplyWaste::getDeleted, bo.getDeleted());
        lqw.eq(bo.getBatchId() != null, ApplyWaste::getBatchId, bo.getBatchId());
        return lqw;
    }

    /**
     * 新增_报废申请/审批  员工可以不停的新增
     */
    @Override
    @Transactional
    @DistributedLock(lockKey = "#bo.objectName+#bo.batchId", waitTimeInMill = 1000)
    public Boolean employeeApply(ApplyWasteBo bo) {

        confirmBatchAndProducts(bo);
        ApplyWaste add = BeanUtil.toBean(bo, ApplyWaste.class);
        // 修改逻辑
        if (ObjectUtil.isNotEmpty(bo.getId())) {
            LambdaQueryWrapper<ApplyWaste> lqw = Wrappers.lambdaQuery();
            lqw.eq(ApplyWaste::getId, bo.getId());
            // 获取上次申请
            List<ApplyWaste> applyWastes = baseMapper.selectList(lqw);

            // 获取当前 批次+物品 库存
            LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = Wrappers.lambdaQuery();
            stockLambdaQueryWrapper.eq(Stock::getBatchId, bo.getBatchId());
            stockLambdaQueryWrapper.eq(Stock::getProductsId, bo.getProductsId());
            List<Stock> stockList = stockMapper.selectList(stockLambdaQueryWrapper);

            // 当前库存量
            Long productsNum = stockList.get(0).getProductsNum();
            // 当前库存待报废数量
            Long productsUnqualified = Long.parseLong(bo.getObjectAmount());
            Long lastApplyUnqualified = 0L;

            if (ObjectUtil.isNotEmpty(applyWastes)) {
                if (StringUtils.isNumeric(applyWastes.get(0).getObjectAmount())) {
                    // 上次申请的报废数量
                    lastApplyUnqualified = Long.parseLong(applyWastes.get(0).getObjectAmount());
                } else {
                    throw new ServiceException("上次报废数量存在问题");
                }
            }
            if (productsNum < stockList.get(0).getProductsUnqualified() + productsUnqualified - lastApplyUnqualified) {
                throw new ServiceException("库存中物品数量不足,无法修改申请报废，请重新填写数量");
            }
            // 编辑申请，只需要操作 报废数量字段
            stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() + productsUnqualified - lastApplyUnqualified);
            if (stockMapper.updateById(stockList.get(0)) <= 0) {
//            if (!updateStockWithLock(stockList.get(0))) {
                throw new ServiceException("库存更新失败");
            }
            // id不为空则为修改
            add.setUpdateTime(LocalDateTime.now());
            return updateById(add);
        } else {
            // 新增逻辑
            if (!handleStockByApply(bo, null)) {
                throw new ServiceException("操作失败");
            }
            // 还得操作stock表
            add.setCreateTime(LocalDateTime.now());
            add.setUpdateTime(LocalDateTime.now());
            return save(add);
        }

    }

    /**
     * 新增_报废申请/审批
     */
    @Transactional
    @DistributedLock(lockKey = "#bo.objectName+#bo.batchId", waitTimeInMill = 1000)
    @Override
    public Boolean managerAdvice(ApplyWasteBo bo) {
        confirmBatchAndProducts(bo);
        // 2.检查物品和批次和申请人匹配的数据
        LambdaQueryWrapper<ApplyWaste> lqw = Wrappers.lambdaQuery();
        lqw.eq(ApplyWaste::getId, bo.getId());
        List<ApplyWaste> applyWastes = baseMapper.selectList(lqw);
        ApplyWaste updateApply = BeanUtil.toBean(bo, ApplyWaste.class);

        if (ObjectUtil.isNotEmpty(applyWastes)) {
            // 若当前已经是不同意 -> 要变更为同意
            if (Objects.equals(applyWastes.get(0).getFlag(), LaoBaoConstants.BF_DISAGREE_APPLY_FLAG) && Objects.equals(bo.getFlag(), LaoBaoConstants.BF_AGREE_APPLY_FLAG)) {
                LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = Wrappers.lambdaQuery();
                stockLambdaQueryWrapper.eq(Stock::getBatchId, bo.getBatchId());
                stockLambdaQueryWrapper.eq(Stock::getProductsId, bo.getProductsId());
                List<Stock> stockList = stockMapper.selectList(stockLambdaQueryWrapper);
                // 库存总数
                Long productsNum = stockList.get(0).getProductsNum();
                // 不同意的申请的报废数
                Long lastProductsUnqualified = 0L;

                if (ObjectUtil.isNotEmpty(applyWastes)) {
                    if (StringUtils.isNumeric(applyWastes.get(0).getObjectAmount())) {
                        lastProductsUnqualified = Long.parseLong(applyWastes.get(0).getObjectAmount());
                    } else {
                        throw new ServiceException("上次报废数量存在问题");
                    }
                }
                if (productsNum - lastProductsUnqualified < 0) {
                    throw new ServiceException("库存不足，请重新申请");
                }
                stockList.get(0).setProductsNum(productsNum - lastProductsUnqualified);
                // 主管 不同意变更为同意，只需要变更库存即可
                if (stockMapper.updateById(stockList.get(0)) <= 0) {
//                if (!updateStockWithLock(stockList.get(0))) {
                    throw new ServiceException("库存更新失败");
                }
                // 更新状态
                applyWastes.get(0).setFlag(LaoBaoConstants.BF_AGREE_APPLY_FLAG);
                return updateById(applyWastes.get(0));

            }
            // 若当前已经是同意 要变更为不同意
            else if (Objects.equals(applyWastes.get(0).getFlag(), LaoBaoConstants.BF_AGREE_APPLY_FLAG) && Objects.equals(bo.getFlag(), LaoBaoConstants.BF_DISAGREE_APPLY_FLAG)) {
                throw new ServiceException("已同意无法变更");
            } else {
                // 操作库存
                if (!handleStockByApply(bo, applyWastes.get(0))) {
                    throw new ServiceException("库存更新失败");
                }

                updateApply.setId(applyWastes.get(0).getId());
                updateApply.setUpdateTime(LocalDateTime.now());
                if (!updateById(updateApply)) {
                    throw new ServiceException("操作失败");
                }
            }
        } else {
            throw new ServiceException("无法找到对应申请");
        }
        return true;
    }


    /**
     * 根据申请状态处理库存
     *
     * @param bo
     * @return
     */
    @DistributedLock(lockKey = "#bo.objectName+#bo.batchId", waitTimeInMill = 1000)
    public Boolean handleStockByApply(ApplyWasteBo bo, ApplyWaste lastApplyWaste) {

        //先查一下 stock
        LambdaQueryWrapper<Stock> lqw = Wrappers.lambdaQuery();
        lqw.eq(Stock::getBatchId, bo.getBatchId());
        lqw.eq(Stock::getProductsId, bo.getProductsId());
        List<Stock> stockList = stockMapper.selectList(lqw);
        if (ObjectUtil.isNotEmpty(stockList)) {
            // 更新报废申请数量
            // 总数量
            Long productsNum = stockList.get(0).getProductsNum();
            Long productsUnqualified = 0L;
            Long lastProductsUnqualified = 0L;
            if (StringUtils.isNumeric(bo.getObjectAmount())) {
                productsUnqualified = Long.parseLong(bo.getObjectAmount());
            } else {
                throw new ServiceException("请输入正确的报废数量");
            }
            if (ObjectUtil.isNotEmpty(lastApplyWaste)) {
                if (StringUtils.isNumeric(lastApplyWaste.getObjectAmount())) {
                    lastProductsUnqualified = Long.parseLong(lastApplyWaste.getObjectAmount());
                } else {
                    throw new ServiceException("上次报废数量存在问题");
                }
            }
            // 员工若要执行申请状态 这里是单纯新增
            if (Objects.equals(bo.getFlag(), LaoBaoConstants.BF_APPLY_FLAG)) {

                if (productsNum < stockList.get(0).getProductsUnqualified() + productsUnqualified) {
                    throw new ServiceException("库存中物品数量不足,无法申请报废，请重新填写数量");
                }
                // 设置报废申请数量 员工单纯新增，只需要操作库存的报废数量
                stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() + productsUnqualified);
                return stockMapper.updateById(stockList.get(0)) > 0;
//                return updateStockWithLock(stockList.get(0));
            }

            // 主管 若要执行 申请 -> 同意状态
            if (Objects.equals(bo.getFlag(), LaoBaoConstants.BF_AGREE_APPLY_FLAG)) {

                if (stockList.get(0).getProductsNum() - productsUnqualified < 0) {
                    throw new ServiceException("库存中物品数量不足,无法报废");
                }
                // 设置报废申请数量
                if (stockList.get(0).getProductsUnqualified() - productsUnqualified < 0) {
                    stockList.get(0).setProductsUnqualified(0L);
                }else{
                    stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() - productsUnqualified);
                }

                // 设置总的申请数量
                stockList.get(0).setProductsNum(stockList.get(0).getProductsNum() - productsUnqualified);
                return stockMapper.updateById(stockList.get(0)) > 0;
//                return updateStockWithLock(stockList.get(0));
            }
            // 主管若要执行 申请 -> 不同意状态
            if (Objects.equals(bo.getFlag(), LaoBaoConstants.BF_DISAGREE_APPLY_FLAG)) {
                // 设置报废申请数量
                if (stockList.get(0).getProductsUnqualified() - productsUnqualified < 0) {
                    stockList.get(0).setProductsUnqualified(0L);
                }else{
                    stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() - productsUnqualified);
                }
                return stockMapper.updateById(stockList.get(0)) > 0;
//                return updateStockWithLock(stockList.get(0));
            }


        } else {
            throw new ServiceException("库存中无批次和物品的信息");
        }
        return false;

    }


    private ApplyWasteBo confirmBatchAndProducts(ApplyWasteBo bo) {
        // 1.检查物品和批次是否存在
        // 根据物品名称查询物品
        LambdaQueryWrapper<Products> productsLambdaQueryWrapper = Wrappers.lambdaQuery();
        productsLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(bo.getObjectName()), Products::getName, bo.getObjectName());
        productsLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(bo.getProductsId()), Products::getId, bo.getProductsId());
        List<Products> products = productsMapper.selectList(productsLambdaQueryWrapper);
        if (products.size() != 1) {
            throw new RuntimeException("物品检查失败");
        }
        // 设置物品id和name
        bo.setProductsId(products.get(0).getId());
        bo.setObjectName(products.get(0).getName());
        // 根据批次id查询批次
        LambdaQueryWrapper<Batch> batchLambdaQueryWrapper = Wrappers.lambdaQuery();
        batchLambdaQueryWrapper.eq(Batch::getId, bo.getBatchId());
        List<Batch> batches = batchMapper.selectList(batchLambdaQueryWrapper);
        if (batches.size() == 0) {
            throw new RuntimeException("批次不存在");
        }
        return bo;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ApplyWaste entity) {

    }

    /**
     * 批量删除_报废申请/审批
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 修改_报废申请/审批
     */
    @Override
    public Boolean updateByBo(ApplyWasteBo bo) {
        ApplyWaste update = BeanUtil.toBean(bo, ApplyWaste.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 处理员工的申请撤回
     *
     * @param
     * @return
     */
    @Override
    public Boolean handleWithdrawApply(List<Long> ids) {
        // 确认批次和物品信息

        // 1.查询出申请信息
        List<ApplyWaste> applyWastes = baseMapper.selectBatchIds(ids);

        if (ObjectUtil.isNotEmpty(applyWastes)) {
            applyWastes.forEach(applyWaste -> {

                // 2.查询出库存信息，对其中的报废申请数量进行修改
                LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = Wrappers.lambdaQuery();
                stockLambdaQueryWrapper.eq(Stock::getBatchId, applyWaste.getBatchId());
                stockLambdaQueryWrapper.eq(Stock::getProductsId, applyWaste.getProductsId());
                List<Stock> stockList = stockMapper.selectList(stockLambdaQueryWrapper);
                if (ObjectUtil.isNotEmpty(stockList)) {
                    // 设置当前申请的报废数量，防止误操作
                    applyWaste.setObjectAmount(applyWastes.get(0).getObjectAmount());
                    if (stockList.get(0).getProductsUnqualified() - Long.parseLong(applyWaste.getObjectAmount()) < 0) {
                        throw new ServiceException("报废数量恢复异常");
                    }
                    // 处理库存 撤回申请 撤回员工申请，只需要操作库存中的报废数量
                    stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() - Long.parseLong(applyWaste.getObjectAmount()));
                    if (stockMapper.updateById(stockList.get(0)) <= 0) {
//                    if (!updateStockWithLock(stockList.get(0))) {
                        throw new ServiceException("撤回失败");
                    }

                    if (baseMapper.deleteById(applyWaste) == 0) {
                        throw new ServiceException("撤回失败");
                    }
                } else {
                    throw new ServiceException("库存中无批次和物品的信息");
                }
            });
        } else {
            throw new ServiceException("未找到对应的申请，撤销失败");
        }
        return true;
    }

    /**
     * 处理主管的申请撤回
     *
     * @param
     * @return
     */
    @Override
    public Boolean handleWithdrawAdvice(List<Long> ids) {

        // 1.查询出申请信息
        List<ApplyWaste> applyWastes = baseMapper.selectBatchIds(ids);

        if (ObjectUtil.isNotEmpty(applyWastes)) {
            applyWastes.forEach(applyWaste -> {

                // 2.查询出库存信息，对其中的报废申请数量进行修改
                LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = Wrappers.lambdaQuery();
                stockLambdaQueryWrapper.eq(Stock::getBatchId, applyWaste.getBatchId());
                stockLambdaQueryWrapper.eq(Stock::getProductsId, applyWaste.getProductsId());
                List<Stock> stockList = stockMapper.selectList(stockLambdaQueryWrapper);
                if (ObjectUtil.isNotEmpty(stockList)) {

                    Long lastApplyAmount = 0L;
                    if (ObjectUtil.isNotEmpty(applyWaste)) {
                        if (StringUtils.isNumeric(applyWaste.getObjectAmount())) {
                            lastApplyAmount = Long.parseLong(applyWaste.getObjectAmount());
                        } else {
                            throw new ServiceException("请输入正确的报废数量");
                        }
                    }
                    // 若是当前申请状态为同意,需要撤回
                    if (Objects.equals(applyWaste.getFlag(), LaoBaoConstants.BF_AGREE_APPLY_FLAG)) {
                        // 设置报废申请数量
                        stockList.get(0).setProductsNum(stockList.get(0).getProductsNum() + lastApplyAmount); // 补上报废数量
                        stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() + lastApplyAmount); // 补上报废数量
                    }
                    // 若是当前申请状态为不同意,需要撤回
                    else if (Objects.equals(applyWaste.getFlag(), LaoBaoConstants.BF_DISAGREE_APPLY_FLAG)) {
                        stockList.get(0).setProductsUnqualified(stockList.get(0).getProductsUnqualified() + lastApplyAmount); // 补上报废数量
                    }

                    // 恢复当前申请状态 并更新
                    applyWaste.setFlag(LaoBaoConstants.BF_APPLY_FLAG);
                    applyWaste.setUpdateTime(LocalDateTime.now());

                    if (baseMapper.updateById(applyWaste) <= 0) {
                        throw new ServiceException("更新申请失败");
                    }
                    if (stockMapper.updateById(stockList.get(0)) <= 0) {
                        throw new ServiceException("更新库存失败");
                    }

                } else {
                    throw new ServiceException("库存中无批次和物品的信息");
                }
            });
        } else {
            throw new ServiceException("未找到对应的申请，撤销失败");
        }
        return true;
    }


    /**
     * 根据日期自动开启报废申请
     */
    @Transactional
    @Override
    @Scheduled(cron = "0 0 * * * *")
    public void bfAutoApplyScheduled() {
        LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = Wrappers.lambdaQuery();
        stockLambdaQueryWrapper.lt(Stock::getEndDate, LocalDateTime.now());
        List<Stock> stockList = stockMapper.selectList(stockLambdaQueryWrapper);
        stockList.forEach(stock -> {
            // 先查询所有关于这个批次+物品的报废申请
            if (ObjectUtil.isAllNotEmpty(stock.getProductsId(), stock.getBatchId())) {
                ApplyWasteBo applyWasteBo = new ApplyWasteBo();
                applyWasteBo.setProductsId(stock.getProductsId());
                applyWasteBo.setBatchId(stock.getBatchId());
                applyWasteBo.setApplicant("自动报废");
                // 设置报废数量
                applyWasteBo.setObjectAmount(String.valueOf(stock.getProductsNum() - stock.getProductsUnqualified()));
                // 设置申请状态
                applyWasteBo.setFlag(LaoBaoConstants.BF_APPLY_FLAG);

                // 查询 自动报废已提交 的申请 并删除
                LambdaQueryWrapper<ApplyWaste> lqw = Wrappers.lambdaQuery();
                lqw.eq(ApplyWaste::getApplicant, "自动报废");
                lqw.eq(ApplyWaste::getProductsId, stock.getProductsId());
                lqw.eq(ApplyWaste::getBatchId, stock.getBatchId());
                List<Integer> collect = baseMapper.selectList(lqw).stream().map(ApplyWaste::getId).collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(collect)) {
                    if (!baseMapper.deleteBatch(collect)) {
                        System.out.println("自动提交删除失败");
                    }
                }


                if (!employeeApply(applyWasteBo)) {
                    System.out.println("自动提交报废申请失败");
                }
            } else {
                System.out.println("自动提交报废申请失败");
            }

        });
    }


}
